package org.jeecg.modules.outOrder1.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.modules.inOrder1.entity.InOrder1;
import org.jeecg.modules.inOrder1.entity.InOrderZi;
import org.jeecg.modules.reportLabel.entity.ReportLabel;
import org.jeecg.modules.reportLabel.service.IReportLabelService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.outOrder1.entity.OutOrderZi;
import org.jeecg.modules.outOrder1.entity.OutOrder1;
import org.jeecg.modules.outOrder1.vo.OutOrder1Page;
import org.jeecg.modules.outOrder1.service.IOutOrder1Service;
import org.jeecg.modules.outOrder1.service.IOutOrderZiService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 出库单
 * @Author: jeecg-boot
 * @Date: 2024-01-12
 * @Version: V1.0
 */
@Api(tags = "出库单")
@RestController
@RequestMapping("/outOrder1/outOrder1")
@Slf4j
public class OutOrder1Controller {
    @Autowired
    private IOutOrder1Service outOrder1Service;
    @Autowired
    private IOutOrderZiService outOrderZiService;
    @Autowired
    private IReportLabelService reportLabelService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 分页列表查询
     *
     * @param outOrder1
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "出库单-分页列表查询")
    @ApiOperation(value = "出库单-分页列表查询", notes = "出库单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(OutOrder1 outOrder1,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<OutOrder1> queryWrapper = QueryGenerator.initQueryWrapper(outOrder1, req.getParameterMap());
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.likeRight("sys_org_code", user.getOrgCode());
        Page<OutOrder1> page = new Page<OutOrder1>(pageNo, pageSize);
        IPage<OutOrder1> pageList = outOrder1Service.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 出库任务领取-分页列表查询
     *
     * @param outOrder1
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "出库任务领取-分页列表查询")
    @ApiOperation(value = "出库任务领取-分页列表查询", notes = "出库任务领取-分页列表查询")
    @GetMapping(value = "/receive")
    public Result<?> receive(OutOrder1 outOrder1,
                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                             HttpServletRequest req) {
        QueryWrapper<OutOrder1> queryWrapper = QueryGenerator.initQueryWrapper(outOrder1, req.getParameterMap());
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.likeRight("sys_org_code", user.getOrgCode());
        queryWrapper.eq("is_hang_up", 0);
        List<String> role = sysUserService.getRole(user.getUsername());
        if (role.stream().allMatch(s -> s.equals("tally"))) {
            queryWrapper.eq("out_order_status", 8);
        } else if (role.stream().allMatch(s -> s.equals("driver"))){
            queryWrapper.eq("out_order_status", 6);
        }
        Page<OutOrder1> page = new Page<OutOrder1>(pageNo, pageSize);
        IPage<OutOrder1> pageList = outOrder1Service.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "出库单-根据人名、入库单状态查询所有入库单")
    @ApiOperation(value = "出库单-根据人名、入库单状态查询所有入库单",
            notes = "出库单-根据人名、入库单状态查询所有入库单(0:查询全部)")
    @GetMapping("/getByStatusAndName")
    public Result<?> getByStatusAndName(@RequestParam(name = "status", defaultValue = "0") Integer status,
                                        @RequestParam(name = "tallyClerk", required = false) String tallyClerk,
                                        @RequestParam(name = "truckDriver", required = false) String truckDriver) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<OutOrder1> wrapper = Wrappers.lambdaQuery();
        wrapper.likeRight(OutOrder1::getSysOrgCode, user.getOrgCode());
        List<OutOrder1> list;
        if (status != 0) {
            wrapper.eq(OutOrder1::getOutOrderStatus, status);
        }
        if (tallyClerk != null && !tallyClerk.trim().isEmpty()) {
            wrapper.eq(OutOrder1::getTallyClerk, tallyClerk);
        }
        if (truckDriver != null && !truckDriver.trim().isEmpty()) {
            wrapper.eq(OutOrder1::getTruckDriver, truckDriver);
        }
        wrapper.orderByAsc(OutOrder1::getOutOrderStatus);
        list = outOrder1Service.list(wrapper);
        return Result.OK(list);
    }

    @GetMapping("/operateForApp")
    public Result<?> operateForApp(OutOrder1 outOrder1,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<OutOrder1> queryWrapper = QueryGenerator.initQueryWrapper(outOrder1, req.getParameterMap());
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.likeRight("sys_org_code", user.getOrgCode());
        List<String> role = sysUserService.getRole(user.getUsername());
        if (role.stream().allMatch(s -> s.equals("tally"))) {
            queryWrapper.eq("out_order_status", 9);
            queryWrapper.eq("tally_clerk", user.getRealname());
        } else if (role.stream().allMatch(s -> s.equals("driver"))){
            queryWrapper.eq("out_order_status", 7);
            queryWrapper.eq("truck_driver", user.getRealname());
        }
        Page<OutOrder1> page = new Page<OutOrder1>(pageNo, pageSize);
        IPage<OutOrder1> pageList = outOrder1Service.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @GetMapping("/recordForApp")
    public Result<?> recordForApp(OutOrder1 outOrder1,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<OutOrder1> queryWrapper = QueryGenerator.initQueryWrapper(outOrder1, req.getParameterMap());
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.likeRight("sys_org_code", user.getOrgCode());
        List<String> role = sysUserService.getRole(user.getUsername());
        if (role.stream().allMatch(s -> s.equals("tally"))) {
            queryWrapper.gt("out_order_status", 9);
            queryWrapper.eq("tally_clerk", user.getRealname());
        } else if (role.stream().allMatch(s -> s.equals("driver"))){
            queryWrapper.gt("out_order_status", 7);
            queryWrapper.eq("truck_driver", user.getRealname());
        }
        Page<OutOrder1> page = new Page<OutOrder1>(pageNo, pageSize);
        IPage<OutOrder1> pageList = outOrder1Service.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param outOrder1Page
     * @return
     */
    @AutoLog(value = "出库单-添加")
    @ApiOperation(value = "出库单-添加", notes = "出库单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody OutOrder1Page outOrder1Page) {
        OutOrder1 outOrder1 = new OutOrder1();
        BeanUtils.copyProperties(outOrder1Page, outOrder1);
        outOrder1Service.saveMain(outOrder1, outOrder1Page.getOutOrderZiList());
        return Result.OK("添加成功！");
    }

    /**
     * 重新命中
     *
     * @param outOrder1Page
     * @return
     */
    @AutoLog(value = "出库单-重新命中")
    @ApiOperation(value = "出库单-重新命中", notes = "出库单-重新命中")
    @PutMapping(value = "/rehit")
    public Result<?> rehit(@RequestBody OutOrder1Page outOrder1Page) {
        OutOrder1 outOrder1 = new OutOrder1();
        BeanUtils.copyProperties(outOrder1Page, outOrder1);
        outOrder1Service.rehit(outOrder1, outOrder1Page.getOutOrderZiList());
        OutOrder1 byId = outOrder1Service.getById(outOrder1);
        if (byId.getOutOrderStatus().equals(11)) {
            return Result.error("命中失败！");
        }
        return Result.OK("命中成功！");
    }

    /**
     * 编辑
     *
     * @param outOrder1Page
     * @return
     */
    @AutoLog(value = "出库单-编辑")
    @ApiOperation(value = "出库单-编辑", notes = "出库单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody OutOrder1Page outOrder1Page) {
        OutOrder1 outOrder1 = new OutOrder1();
        BeanUtils.copyProperties(outOrder1Page, outOrder1);
        OutOrder1 outOrder1Entity = outOrder1Service.getById(outOrder1.getId());
        if (outOrder1Entity == null) {
            return Result.error("未找到对应数据");
        }
        if (outOrder1.getOutOrderStatus() == 10) {
            return Result.error("出库单已完结，禁止编辑！");
        }
        outOrder1Service.updateMain(outOrder1, outOrder1Page.getOutOrderZiList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库单-通过id删除")
    @ApiOperation(value = "出库单-通过id删除", notes = "出库单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        outOrder1Service.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "出库单-批量删除")
    @ApiOperation(value = "出库单-批量删除", notes = "出库单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.outOrder1Service.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库单-通过id查询")
    @ApiOperation(value = "出库单-通过id查询", notes = "出库单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        OutOrder1 outOrder1 = outOrder1Service.getById(id);
        if (outOrder1 == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(outOrder1);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库子表通过主表ID查询")
    @ApiOperation(value = "出库子表主表ID查询", notes = "出库子表-通主表ID查询")
    @GetMapping(value = "/queryOutOrderZiByMainId")
    public Result<?> queryOutOrderZiListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<OutOrderZi> outOrderZiList = outOrderZiService.selectByMainId(id);
        return Result.OK(outOrderZiList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param outOrder1
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, OutOrder1 outOrder1) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<OutOrder1> queryWrapper = QueryGenerator.initQueryWrapper(outOrder1, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<OutOrder1> queryList = outOrder1Service.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<OutOrder1> outOrder1List = new ArrayList<OutOrder1>();
        if (oConvertUtils.isEmpty(selections)) {
            outOrder1List = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            outOrder1List = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<OutOrder1Page> pageList = new ArrayList<OutOrder1Page>();
        for (OutOrder1 main : outOrder1List) {
            OutOrder1Page vo = new OutOrder1Page();
            BeanUtils.copyProperties(main, vo);
            List<OutOrderZi> outOrderZiList = outOrderZiService.selectByMainId(main.getId());
            vo.setOutOrderZiList(outOrderZiList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "出库单列表");
        mv.addObject(NormalExcelConstants.CLASS, OutOrder1Page.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出库单数据", "导出人:" + sysUser.getRealname(), "出库单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<OutOrder1Page> list = ExcelImportUtil.importExcel(file.getInputStream(), OutOrder1Page.class, params);
                for (OutOrder1Page page : list) {
                    OutOrder1 po = new OutOrder1();
                    BeanUtils.copyProperties(page, po);
                    outOrder1Service.saveMain(po, page.getOutOrderZiList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    /**
     * 任务分配
     */
    @AutoLog(value = "任务分配")
    @ApiOperation(value = "任务分配", notes = "任务分配")
    @PostMapping(value = "/taskAllocation")
    public Result<?> taskAllocation(@RequestBody OutOrder1 outOrder) {
        if (outOrder.getIsHangUp().equals(1)) {
            return Result.error("该单据已挂单禁止操作！");
        }
		//	更新数据库数据
        outOrder1Service.updateById(outOrder);
        return Result.OK();
    }

    @AutoLog(value = "叉车司机领取出库单")
    @ApiOperation(value = "叉车司机领取出库单", notes = "叉车司机领取出库单")
    @PostMapping("/driverReceiveOrder")
    public Result<?> driverReceiveOrder(@RequestBody OutOrder1 outOrder, @RequestParam(name = "username") String username) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = sysUserService.getRole(user.getUsername());
        if (role.stream().noneMatch(s -> s.equals("driver"))) {
            return Result.error("当前登录用户不是叉车司机,请联系叉车司机进行备货操作！");
        }
        return getReceiveResult(username, 7, outOrder);
    }

    @AutoLog(value = "叉车司机扫二维码下架")
    @ApiOperation(value = "叉车司机扫二维码下架", notes = "叉车司机扫二维码下架")
    @PostMapping("/offShelf")
    public Result<?> offShelf(@RequestBody OutOrder1 outOrder, @RequestParam String code) {
        Integer isHangUp = outOrder.getIsHangUp();
        if (1 == isHangUp) {
            return Result.error("此单已挂单,请联系管理员解挂后再进行操作！");
        }
        LambdaQueryWrapper<ReportLabel> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ReportLabel::getBarCode, code);
        List<ReportLabel> labels = reportLabelService.list(wrapper);
        if (labels == null || labels.isEmpty()) {
            return Result.error("当前库内无此二维码信息！请重新尝试扫码！");
        }
        if (labels.stream().allMatch(label -> label.getOutOrderId() == null || !label.getOutOrderId().equals(outOrder.getId()))) {
            return Result.error("此二维码不属于当前出库单！请重新尝试扫码！");
        }
        if (labels.stream().allMatch(label -> 6 != label.getStatus())) {
            return Result.error("此货物未被出库单命中！请选择对应货物！");
        }

        List<OutOrderZi> outOrderZis = outOrderZiService.selectByMainId(outOrder.getId());
        Map<String, OutOrderZi> map = new HashMap<>();
        for (OutOrderZi orderZi : outOrderZis){
            map.put(orderZi.getLabelNumber(), orderZi);
        }
        List<OutOrderZi> orderZis = new LinkedList<>();
        for (ReportLabel label : labels){
            if (map.containsKey(label.getLabelNumber())){
                label.setStatus(8);
                OutOrderZi outOrderZi = map.get(label.getLabelNumber());
                outOrderZi.setOutOrderStatus(8);
                orderZis.add(outOrderZi);
            }
        }
        reportLabelService.updateBatchById(labels);
        outOrderZiService.updateBatchById(orderZis);

        LambdaQueryWrapper<OutOrderZi> wrapper1 = Wrappers.lambdaQuery();
        wrapper1.eq(OutOrderZi::getOutOrderStatus, 7);
        wrapper1.eq(OutOrderZi::getPid, outOrder.getId());
        List<OutOrderZi> list = outOrderZiService.list(wrapper1);
        if (list.isEmpty()) {
            outOrder.setOutOrderStatus(8);
            outOrder.setStockingTime(new Date());
            if (outOrder.getTallyClerk() != null && !outOrder.getTallyClerk().isEmpty()) {
                outOrder.setOutOrderStatus(9);
            }
            outOrder1Service.updateById(outOrder);
            return Result.OK("操作成功！当前出库单已无新任务");
        } else {
            return Result.OK("操作成功！", list);
        }
    }

    @AutoLog(value = "理货员领取出库单")
    @ApiOperation(value = "理货员领取出库单", notes = "理货员领取出库单")
    @PostMapping("/tallyReceiveOrder")
    public Result<?> tallyReceiveOrder(@RequestBody OutOrder1 outOrder, @RequestParam(name = "username") String username) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = sysUserService.getRole(user.getUsername());
        if (role.stream().noneMatch(s -> s.equals("tally"))) {
            return Result.error("当前登录用户不是理货员,请联系理货员进行出库操作！");
        }
        return getReceiveResult(username, 9, outOrder);
    }

    @AutoLog(value = "理货扫描二维码")
    @ApiOperation(value = "理货扫描二维码", notes = "理货扫描二维码")
    @PostMapping("/checkCode")
    public Result<?> checkCode(@RequestBody OutOrder1 outOrder, @RequestParam(name = "code") String code) {
        Integer isHangUp = outOrder.getIsHangUp();
        if (1 == isHangUp) {
            return Result.error("此单已挂单,请联系管理员解挂后再进行操作！");
        }
        LambdaQueryWrapper<ReportLabel> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ReportLabel::getBarCode, code);
        List<ReportLabel> labels = reportLabelService.list(wrapper);
        if (labels == null || labels.isEmpty()) {
            return Result.error("当前库内无此二维码信息！请重新尝试扫码！");
        }
        if (labels.stream().anyMatch(label -> label.getOutOrderId() == null || !label.getOutOrderId().equals(outOrder.getId()))) {
            return Result.error("此二维码不属于当前出库单！请重新尝试扫码！");
        }
        if (labels.stream().anyMatch(label -> 8 != label.getStatus())) {
            return Result.error("此货物未备货！请先完成备货！");
        }
        if (labels.stream().anyMatch(label -> 2 == label.getLockStatus())){
            return Result.error("此货物超过48小时未出库,已自动锁定,请联系管理员解锁！");
        }
        if (labels.stream().anyMatch(label -> 1 == label.getLockStatus())){
            ReportLabel reportLabel = labels.get(0);
            long time = reportLabel.getInDate().getTime();
            long l = System.currentTimeMillis();
            long cha = l - time;
            double result = cha * 1.0 / (1000 * 60 * 60);
            if(result>=48){
                List<ReportLabel> list = labels.stream().peek(label -> label.setLockStatus(2)).collect(Collectors.toList());
                reportLabelService.updateBatchById(list);
                return Result.error("此货物超过48小时未出库,已自动锁定,请联系管理员解锁！");//说明小于24小时
            }
        }
        List<OutOrderZi> outOrderZis = outOrderZiService.selectByMainId(outOrder.getId());
        Map<String, OutOrderZi> map = new HashMap<>();
        List<OutOrderZi> orderZis = new LinkedList<>();
        for (OutOrderZi outOrderZi : outOrderZis) {
            map.put(outOrderZi.getLabelNumber(), outOrderZi);
        }
        for (ReportLabel label : labels){
            int activated = label.getActivated();
            if (activated > 0){
                label.setStatus(14);
            } else if (activated == 0){
                label.setStatus(10);
            } else {
                return Result.error("剩余库存数异常,请联系管理员检查库存");
            }
            OutOrderZi outOrderZi = map.get(label.getLabelNumber());
            outOrderZi.setOutOrderStatus(10);
            orderZis.add(outOrderZi);
        }
        reportLabelService.updateBatchById(labels);
        outOrderZiService.updateBatchById(orderZis);

        LambdaQueryWrapper<OutOrderZi> wrapper1 = Wrappers.lambdaQuery();
        wrapper1.eq(OutOrderZi::getOutOrderStatus, 9);
        wrapper1.eq(OutOrderZi::getPid, outOrder.getId());
        List<OutOrderZi> list = outOrderZiService.list(wrapper1);
        if (list.isEmpty()) {
            outOrder.setOutOrderStatus(10);
            outOrder.setStockingTime(new Date());
            outOrder1Service.updateById(outOrder);
            return Result.OK("操作成功！当前出库单已无新任务");
        } else {
            return Result.OK("操作成功！", list);
        }
    }

    @AutoLog(value = "理货扫确认出库")
    @ApiOperation(value = "理货扫确认出库", notes = "理货扫确认出库")
    @PostMapping("/checkOutOrder")
    public Result<?> checkOutOrder(@RequestBody OutOrder1 outOrder) {
        Integer isHangUp = outOrder.getIsHangUp();
        if (1 == isHangUp) {
            return Result.error("此单已挂单,请联系管理员解挂后再进行操作！");
        }
        List<OutOrderZi> outOrderZis = outOrderZiService.selectByMainId(outOrder.getId());
        for (OutOrderZi outOrderZi : outOrderZis) {
            outOrderZi.setOutOrderStatus(10);
        }
        LambdaQueryWrapper<ReportLabel> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ReportLabel::getOutOrderId, outOrder.getId());
        List<ReportLabel> labels = reportLabelService.list(wrapper);
        for (ReportLabel label : labels){
            int activated = label.getActivated();
            if (activated > 0){
                label.setStatus(14);
            } else if (activated == 0){
                label.setStatus(10);
            } else {
                return Result.error("剩余库存数异常,请联系管理员检查库存");
            }
        }
        reportLabelService.updateBatchById(labels);
        outOrderZiService.updateBatchById(outOrderZis);
        LambdaQueryWrapper<OutOrderZi> wrapper1 = Wrappers.lambdaQuery();
        wrapper1.eq(OutOrderZi::getOutOrderStatus, 9);
        wrapper1.eq(OutOrderZi::getPid, outOrder.getId());
        List<OutOrderZi> list = outOrderZiService.list(wrapper1);
        if (list.isEmpty()) {
            outOrder.setOutOrderStatus(10);
            outOrder.setStockingTime(new Date());
            outOrder1Service.updateById(outOrder);
            return Result.OK("操作成功！当前出库单已无新任务");
        } else {
            return Result.OK("操作成功！", list);
        }
    }

    @NotNull
    private Result<?> getReceiveResult(String username, int val, OutOrder1 outOrder) {
        Integer isHangUp = outOrder.getIsHangUp();
        if (1 == isHangUp) {
            return Result.error("此单已挂单,请联系管理员解挂后领取！");
        }
        int outOrderStatus = outOrder.getOutOrderStatus();
        if (outOrderStatus != val-1){
            return Result.error("当前单据状态不符合要求,无法领取！");
        }
        LambdaQueryWrapper<OutOrder1> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(OutOrder1::getTruckDriver, username);
        wrapper.eq(OutOrder1::getOutOrderStatus, val);
        wrapper.eq(OutOrder1::getIsHangUp, 0);
        List<OutOrder1> list = outOrder1Service.list(wrapper);
        if (list.isEmpty()) {
            outOrder.setOutOrderStatus(val);
            if (7 == val) {
                outOrder.setTruckDriver(username);
                outOrder.setStockingTaskTime(new Date());
            } else if (9 == val) {
                outOrder.setTallyClerk(username);
                outOrder.setTallyTaskTime(new Date());
            }
            List<OutOrderZi> outOrderZis = outOrderZiService.selectByMainId(outOrder.getId());
            for (OutOrderZi outOrderZi : outOrderZis) {
                outOrderZi.setOutOrderStatus(val);
            }
            outOrder1Service.updateMain(outOrder, outOrderZis);
            return Result.OK("领取成功!");
        }
        return Result.error("你当前有未完成的出库单,请先作业！");
    }

}
